<template>
  <div class="img-verify">
    <canvas ref="verify" :width="width" :height="height" @click="handleDraw"></canvas>
  </div>
</template>
<script lang="ts">
import {defineComponent, reactive, onMounted, ref, toRefs } from 'vue'
import {randomNum,randomColor} from "@/utils"
export default defineComponent({
  name: 'tImgCode',
  setup() {
    const verify = ref();
    const state = reactive({
      pool: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // 字符串
      width: 100,
      height: 30,
      imgCode: ''
    });
    onMounted(() => {
      state.imgCode = draw()
    });
    // 点击图片重新绘制
    const handleDraw = () => {
      state.imgCode = draw()
    }
    // 绘制图片
    const draw = () => {
      if(!verify.value)return '';
      const ctx = verify.value.getContext('2d')
      ctx.fillStyle = randomColor(180, 230)
      ctx.fillRect(0, 0, state.width, state.height)
      // 定义paramText
      let imgCode = ''
      // 4.随机产生字符串，并且随机旋转
      for (let i = 0; i < 4; i++) {
        const text = state.pool[randomNum(0, state.pool.length)]
        imgCode += text
        const fontSize = randomNum(18, 40)
        const deg = randomNum(-30, 30)
        ctx.font = fontSize + 'px Simhei'
        ctx.textBaseline = 'top'
        ctx.fillStyle = randomColor(80, 150)
        ctx.save()
        ctx.translate((state.width/4) * i + 15, 15)
        ctx.rotate((deg * Math.PI) / 180)
        ctx.fillText(text, -15 + 5, -15)
        ctx.restore()
      }
      // 随机产生5条干扰线,干扰线的颜色要浅一点
      for (let i = 0; i < 5; i++) {
        ctx.beginPath()
        ctx.moveTo(randomNum(0, state.width), randomNum(0, state.height))
        ctx.lineTo(randomNum(0, state.width), randomNum(0, state.height))
        ctx.strokeStyle = randomColor(180, 230)
        ctx.closePath()
        ctx.stroke()
      }
      // 随机产生40个干扰的小点
      for (let i = 0; i < 40; i++) {
        ctx.beginPath()
        ctx.arc(randomNum(0, state.width), randomNum(0, state.height), 1, 0, 2 * Math.PI)
        ctx.closePath()
        ctx.fillStyle = randomColor(150, 200)
        ctx.fill()
      }
      return imgCode
    }
    return {
      ...toRefs(state),
      verify,
      handleDraw
    }
  }
})
</script>
<style lang="scss" scope>
.img-verify {
  line-height: 0;
  canvas {
    cursor: pointer;
  }
}
</style>